let audioContext = null;
let isGlobalMusicPlaying = false;
let isPageSpecificMusicPaused = false; // 添加这个全局变量表示特定页面音乐暂停状态

function playBackgroundMusic() {
  if (!audioContext || audioContext.paused) {
    audioContext = uni.createInnerAudioContext();
    audioContext.autoplay = true;
    audioContext.loop = true;
    audioContext.src = 'https://xnlv-test.lizxx.com/image/xnlv/static/yinyue/yanyuxiaozheng.mp3';
    isGlobalMusicPlaying = true;
  } else {
     audioContext.play();
   }
 }

function pauseBackgroundMusic() {
  if (audioContext &&!audioContext.paused) {
    audioContext.pause();
    isGlobalMusicPlaying = false;
  }
}

class PageSpecificMusicManager {
  static instance = null;

  constructor() {
    if (!PageSpecificMusicManager.instance) {
      this.pageSpecificAudioContext = null;
      this.isPlaying = false;
      PageSpecificMusicManager.instance = this;
    }
    return PageSpecificMusicManager.instance;
  }

  playPageSpecificMusic() {
    if (!this.pageSpecificAudioContext || this.pageSpecificAudioContext.paused ||!this.isPlaying || isPageSpecificMusicPaused) {
      if (!this.pageSpecificAudioContext) {
        this.pageSpecificAudioContext = uni.createInnerAudioContext();
        this.pageSpecificAudioContext.autoplay = true;
        this.pageSpecificAudioContext.loop = true;
        this.pageSpecificAudioContext.src = 'https://xnlv-test.lizxx.com/image/xnlv/static/yinyue/wainizhongguou.mp3';
      } else {
        this.pageSpecificAudioContext.play();
      }
      this.isPlaying = true;
      // 暂停全局音乐
      pauseBackgroundMusic();
    }
  }

  pausePageSpecificMusic() {
    if (this.pageSpecificAudioContext &&!this.pageSpecificAudioContext.paused) {
      this.pageSpecificAudioContext.pause();
      this.isPlaying = false;
      isPageSpecificMusicPaused = true; // 设置暂停状态
    }
  }
}

const pageSpecificMusicManager = new PageSpecificMusicManager();

// 添加一个方法来设置 isPageSpecificMusicPaused 的值
function setPageSpecificMusicPaused(paused) {
  isPageSpecificMusicPaused = paused;
}

export { playBackgroundMusic, pauseBackgroundMusic, pageSpecificMusicManager, isGlobalMusicPlaying, isPageSpecificMusicPaused, setPageSpecificMusicPaused };